package com.test.javafaq_portal.controller;


import com.test.javafaq_portal.entity.Answer;
import com.test.javafaq_portal.service.IAnswerService;
import com.test.javafaq_portal.vo.AnswerVo;
import com.test.javafaq_portal.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author test.com
 * @since 2025-04-11
 */
@RestController
@Slf4j
@RequestMapping("/v1/answers")
public class AnswerController {

    @Autowired
    IAnswerService answerService;
    //  localhost:8080/v1/answers/question/150
    @GetMapping("/question/{id}")
    public R<List<Answer>> questionAnswers(@PathVariable Integer id){
        if(id == null)
            return R.notFound("ID不存在!");
        List<Answer> answers = answerService.getAnswersByQuestionId(id);
        return R.ok(answers);
    }
    @PostMapping
    @PreAuthorize("hasRole('ROLE_TEACHER')")
    public R postAnswer(@Validated AnswerVo answerVo, BindingResult res){
        if(res.hasErrors()){
            String msg=res.getFieldError().getDefaultMessage();
            log.debug(msg);
            return R.unproecsableEntity(msg);
        }
        log.debug("开始新增回答:{}",answerVo);
        Answer answer = answerService.answerQuestion(answerVo);
        return R.create(answer);
    }
}
